
// 所有数据
	var allData = {
		carPlateList:[],
		carPlate: false,
		carPlateId: false,
		lotSn:'',
		exitName:'',
		parkingFeeResult:'',
		lotName: '',
		parkingInfo: null,
		lastQuery: null,
		isDef:false,//车牌是否默认
		isEnable:true,//车场系统是否可用
		isqrcodeAtExit:false//出口扫码
	};
	var _config = {
		timeout: 16000,
	};
	var layer_loading;
	// INIT====>
	try{		
		!function(win, doc,$) {			
			$(function(){
				allData.exitName=$('#exitName').val();
				// 车场名称
				allData.lotName = $('#name').val();
				//车场获取
				getParkingLotInfo(function(){			
					getCarPlates();			
				});	
				//支付按钮高度重置
				intHeight();
				//广告
				setNotice();
				// 出口名称				
				//getUserInfo();	/*		用户信息获取*				
			});
		}(window,document,jQuery);		
	}catch(e){
		var err = e && e.stack ? e.stack : e;
		var xhr = new XMLHttpRequest();
		xhr.open('post',"/log_error",true);
		xhr.send('err=' + err);
		xhr.onreadystatechange = function () {
		    // 这步为判断服务器是否正确响应
		  if (xhr.readyState == 4 && xhr.status == 200) {
		    console.log(xhr.responseText);
		  }
		};
		throw err;
	};
/*通知发布*/	
	var intval=setInterval(function(){
		slider()
	},3000),
		sliderIndex=0,
		len=$('.noticeList li').length;	
	function setNotice(item){		
		if(typeof(item)=='undefined'){
			return;
		}
		try{	
			$('#notice').show();
			var marquee_html='';
			item.forEach(function(value){
				marquee_html+='<span>'+value+'</span>'			
			});			
			$('#notice').find('marquee').html(marquee_html)	;
			
		}catch(err){
			return;
		}
	};	
	function slider(){
		sliderIndex++;
		if(sliderIndex==len){
			sliderIndex=0
			$('.noticeList li').css("margin-left",'0px')	
		}			
		var offset=-sliderIndex*100+"%",
			speed=sliderIndex*500;
		 	window.clearInterval(intval);//防止定时器叠加执行
		$('.noticeList li').eq(sliderIndex-1).animate({"margin-left":offset},speed,"swing",function(){
			intval=setInterval(function(){
						slider()
			},3000)							
		});						
	};			
/*---计算页面高度处理按钮的显示方式----	*/
function intHeight(){
	var H1=$(window).height(),
	H0=$(document).height();
    $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
	if(H0-H1>0){
		$('.footer-button').addClass('fixed');
		$('.hidesubmit').show();		
	}
};
$(window).scroll(function(){
	var H1=$(window).height(),
		H0=$(document).height();
	var scrollTop=$(document).scrollTop();	
	if(H0-H1-scrollTop<=59){
		$('.footer-button').removeClass('fixed');
		$('.hidesubmit').hide();
		$('.footer-button').css("background","#f8f8f8")
	}
	if(H0-H1-scrollTop>59){
		$('.footer-button').addClass('fixed');
		$('.hidesubmit').show();
		$('.footer-button').css("background","rgba(225,225,225,.6)")
	}
});
	// ----------------------主函数
	function payType(){
		var browser = navigator.userAgent.toLowerCase();
		if(browser.match(/Alipay/i)=="alipay"){
			return "alipay";   
		}else if(browser.match(/MicroMessenger/i)=="micromessenger"){
			return "weixin";    
		}else{
			return false;	
		}		
	};
//重置allData中的车牌信息{该车牌用于显示，查询费用，以及提交订单}
	function resetCarPlate(carPlate,carPlateId,text){
		$('.plate-number .content').text(text);
		allData.carPlateId = carPlateId;
		allData.carPlate = carPlate;			
	};	
	function getUserInfo(){
		$.ajax({
			url:'/member/member/getinfo',
			type:'get',
			success:function(result){
				if(result.status==0){
					var headimg=result.datas.headimg;
					$('.avatar').find('img').attr('src',headimg);
				}
			}
		})	
	};
//出口扫码	qrcodeByExit
	function qrcodeByExit(){		
		try{
			var parkingFeeResult=JSON.parse($('#parkingFeeResult').val());				
			allData.parkingFeeResult=parkingFeeResult;		
			allData.isqrcodeAtExit=true;
			if(parkingFeeResult.isSuccess){
				var data=parkingFeeResult;
				allData.parkingInfo = data;				
				var bool=data.calcstarttime==data.entertime;//判断入场时间跟开始计费时间是否相等;
				$('.submit').removeClass('submit-disabled');
				$('.park-time .content').text(toHourMinute(data.parktimeMinute));
				$('.pay-money .money').text(data.fee);
				$('.Einlass .content').text(data.entertime);
				$('.calcstarttime .content').text(data.calcstarttime);
				if(!bool){
					$('.calcstarttime').show();
				}
			}else{
				layer.msg(parkingFeeResult.msg, {icon: 5,shade: [0.8, '#393D49'],time: 1500});	
				$('.park-time .content').text(parkingFeeResult.msg);
				$('.Einlass .content').text(parkingFeeResult.msg);												
			}
		}catch(err){
			return false;
		}
	};
	function getParkingLotInfo(onEnableCallback){	
		$.ajax({
			url:'/member/parkinglot/get',
			type:'get',
			timeout:_config.timeout,
			success:function(result){				
				if(result.status==0){
					$('.park .icon-txt').text(result.datas.name);
					$('.park .exitName').text(allData.exitName);
					allData.lotSn=result.datas.sn;
					var hasMcard=result.datas.isMonthCardChargeEnable;//是否有月卡功能
					allData.isEnable=result.datas.isEnable;//车场缴费系统是否可用										
					if(hasMcard){
						$('.user-table').addClass("col-4");
						$('.col-4').find('.hide').removeClass('hide');	
					}					
					if(!result.datas.isEnable){
						var lay_error=layer.alert('抱歉自助缴费服务暂停，请谅解！', {
							  skin: 'layui-layer-lan' //样式类名
							  ,closeBtn: 0
							  ,anim: 4
							  ,btn: ['关闭']
							}, function(){					
								close();
						});			
						return false;//服务异常
					}else if(payType()=="alipay"){						
						if(!result.datas.isAlipayEnable){
							var lay_error=layer.alert('抱歉当前车场未开通支付宝，请谅解！', {
								  skin: 'layui-layer-lan' //样式类名
								  ,closeBtn: 0
								  ,anim: 4
								  ,btn: ['关闭']
								}, function(){					
									close();
							});			
							return false;								
						}else{
							onEnableCallback();
						}												
					}else if(payType()=="weixin"){
						if(!result.datas.isWeixinEnable){
							var lay_error=layer.alert('抱歉当前车场未开通微信支付，请谅解！', {
								  skin: 'layui-layer-lan' //样式类名
								  ,closeBtn: 0
								  ,anim: 4
								  ,btn: ['关闭']
								}, function(){					
									close();
							});			
							return false;							
						}else{
							onEnableCallback();
						}
					
					}else{
						onEnableCallback();
					}	
				}
			},
		    complete:function(XHR,TextStatus){
		        if(TextStatus=='timeout'){ //超时执行的程序
		            layer.msg("请求超时！", {icon: 5,shade: [0.8, '#393D49'],time: 1000});
		        }
		    }

		})
	};	
	function getCarPlates(){
		layer.load();//
		$.ajax({
			url:'/member/carplate/list',
			type:'post',
			success:function(result){
				//车牌初始化
				if(result.status==0){
					var obj = result.datas;
					var carPlateList="";//车牌列表
					for (var i = 0; i < obj.length; i++) {	
						if(obj[i].isDef){
							allData.isDef=obj[i].isDef;//记录车牌中是否有默认
						};
						carPlateList+="<li data-id='"+obj[i].id+"'>"+obj[i].carPlate+"</li>";					
						$('.plate-select ul').html(carPlateList)
						allData.carPlateList.push(obj[i].carPlate)
					};				
					if (obj.length > 1) {/*多个车牌*/
						if(!allData.isDef){
							resetCarPlate(false,false,'选择车牌')				
						}else{
							obj.forEach(function(currentValue, index, arr){
								  if(currentValue.isDef){
									  resetCarPlate(currentValue.carPlate,currentValue.id,currentValue.carPlate)
								  }				  
			    			});							
						}
					}else{
						if(obj.length == 1){
							resetCarPlate(obj[0].carPlate,obj[0].id,obj[0].carPlate)
						}					
					};
					qrcodeByExit();
	//判断是否出口扫码
					if(allData.isqrcodeAtExit){
						if(allData.parkingInfo){
				//出口扫码,有车牌
							var carPlate=allData.parkingFeeResult.carPlate;
							var html='<div class="carPlateMark">'+carPlate+'</div>';
								resetCarPlate(carPlate,false,carPlate);
							var index=layer.confirm(html, {
								btn: ['刷新','确认','修改'] 
								,title: '请核实您的车牌号'
								,yes: function(index, layero){
								    //点击刷新
									location.reload();
								 }
								,btn2:function(){
									//核实没有问题-查费用、绑定该车牌										
									try{											
											allData.lastQuery = new Date().getTime();																							
											var dataObj={
													 carNum:allData.parkingFeeResult.carPlate,
													 isDef:'true'										
											};										
											var isbind=allData.carPlateList.indexOf(dataObj.carNum);//判断本次车牌是否在绑定列表中									
											if(isbind==-1){										
											//出口扫码并且车牌没有绑定过，绑定该车牌
											 $.ajax({
												 url:"/member/carplate/bind",
												 method:"POST",
												 data:JSON.stringify(dataObj),
												 //async:false,
												 context:this,
												 contentType:"application/json;charset=UTF-8",
												 success:function(result){
													 //绑定成功回显车牌列表
														$.ajax({
															url:'/member/carplate/list',
															type:'post',
															success:function(result){
																if(result.status==0){
																	var obj = result.datas;
																	var carPlateList="";//车牌列表
																	for (var i = 0; i < obj.length; i++) {	
																		if(obj[i].isDef){
																			allData.isDef=obj[i].isDef;//记录车牌中是否有默认
																		};
																		carPlateList+="<li data-id='"+obj[i].id+"'>"+obj[i].carPlate+"</li>";					
																		$('.plate-select ul').html(carPlateList)
																		allData.carPlateList.push(obj[i].carPlate)
																	};																	
																}
															}
														})
												 },
												 error:function(error){
													 console.log('绑定车牌失败')						  					 
												 }
											  })										
											}																													
						
									}catch(err){
										
									};									
									layer.close(index);							
								},
								btn3:function(){								
								  	$(".plate-select").show();
								  	$(".plate-select ul").show();									  	
								}
							});							
						}
												
					}else{
			//是预支付扫码--
						if(allData.carPlate){
							var html='<div class="carPlateMark">'+allData.carPlate+'</div>';						
							var index=layer.confirm(html, {
								  btn: ['刷新','确认','修改'] 
								,title: '请核实您的车牌号'
								 ,btn3: function(index, layero){
									//修改车牌
									  	$(".plate-select").show();
									  	$(".plate-select ul").show();		
								 }
								}, function(){
									//刷新
									 location.reload();						
								}, function(){
									//核实没有问题-查费用
									queryParkingFee();
									layer.close(index);									
								}
							);															
						}else{
					//用户没有默认车牌的情况						
							var len=allData.carPlateList.length;
							if(len>0){
								layer.msg('请选择您要缴费的车牌', {icon: 4,shade: [0.8, '#393D49'],time: 2000});
							}else{
								//用户没有绑定车牌
								layer.msg("没有绑定车牌,请绑定车牌！", {icon: 4,shade: [0.6, '#393D49'],time: 2000},function(){
									location.href = '/member/carplate/bind';
								});									
							}
							
						}						
					}
										
				}else{
					layer.msg(result.res, {icon: 5,shade: [0.8, '#393D49'],time: 2000});
				}

			},
			error:function(res){
				layer.msg(res, {icon: 5,shade: [0.8, '#393D49'],time: 2000});
			},
			complete:function(){
				layer.closeAll('loading');
			}
		})
	};
/*	关闭微信浏览器*/
	function close(){
	    if(typeof AlipayJSBridge != 'undefined')
	        AlipayJSBridge.call('closeWebview');
	    if(typeof WeixinJSBridge != 'undefined')
	        WeixinJSBridge.call('closeWindow');
	}	
	function queryParkingFee(callback){
		if(!allData.carPlate) return false;
		var data = {"carPlate": allData.carPlate};
		allData.lastQuery = new Date().getTime();
		$.ajax({
			url: '/member/park/queryfee',
			type: 'post',
			data: JSON.stringify(data),
			contentType: "application/json;charset=utf-8",
			timeout: _config.timeout,
			beforeSend: function(){
				layer_loading=layer.msg('查询停车费用', {
					  icon: 16
					  ,shade: 0.01
					  ,time: 0
				});		
			},
			success:function(result){
				if (result.status == 0) {
					var data = result.datas;
					if (data.isSuccess) {
						allData.parkingInfo = data;
						var bool=data.calcstarttime==data.entertime;//判断入场时间跟开始计费时间是否相等;
						$('.submit').removeClass('submit-disabled');
						$('.park-time .content').text(toHourMinute(data.parktimeMinute));
						$('.pay-money .money').text(data.fee);
						$('.Einlass .content').text(data.entertime);
						$('.calcstarttime .content').text(data.calcstarttime);	
						if(!bool){
							$('.calcstarttime').show();
						}
						if(callback)
							callback();
					} else {
						allData.parkingInfo = false;
						$('.submit').addClass('submit-disabled');
						$('.park-time .content').text(result.err);
						$('.pay-money .money').text(result.err);
						$('.Einlass .content').text(result.err);
						layer.msg(data.err, {icon: 5,shade: [0.8, '#393D49'],time: 2000});
					}
				} else {
					allData.parkingInfo = false;
					$('.submit').addClass('submit-disabled');
					$('.park-time .content').text(result.err);
					$('.pay-money .money').text('');
					$('.Einlass .content').text(result.err);
					layer.msg(result.err, {icon: 5,shade: [0.8, '#393D49'],time: 2000});
				}
			},
			error: function(){
				layer.msg('连接网络超时，请重试', {icon: 5,shade: [0.8, '#393D49'],time: 2000});
			},
			complete: function(){
				layer.close(layer_loading);
			}
		})
	};	
	//	下单接口 /member/order/create post，json参数(lotOrderNo,carPlateId,money,exit, remark)	
	function createOrder() {
		if(!allData.parkingInfo){
			layer.msg('没有停车信息', {icon: 5,shade: [0.8, '#393D49'],time: 2000});
			return false;
		}
		var $submit = $('.submit');
		if($submit.hasClass('weui-btn_loading')){
			return false;
		};
		if(new Date().getTime()-allData.lastQuery > 1*60*1000){
			queryParkingFee(createOrder);
			return false;
		};			
		$submit.addClass('weui-btn_loading');
		layer_loading=layer.msg('支付中。。。', {
			  icon: 16
			  ,shade: 0.01
			  ,time: 0
		});		
		var loading = true;
		var data = {
			uniqueId: allData.parkingInfo.uniqueId,
			remark: ''
		};
		$.ajax({
			url : '/member/order/create',
			method : "POST",
			data : JSON.stringify(data),
			dataType : "json",
			contentType : "application/json;charset=UTF-8",
			timeout: _config.timeout,
			success : function(result) {
				if (allData.parkingInfo.fee == 0) {
					if (result.status == "0") {
//						location.href = "/member/advert/get";
						showPayMark();
					} else {
						loading?(layer.close(layer_loading),loading = false):false;
						layer.msg(result.err, {icon: 5,shade: [0.8, '#393D49'],time: 2000});
					}
				} else {
					if (result.status == 0) {						
						if (payType() === "weixin") {
							onWeixinPay(result.datas);
						} else if (payType() === "alipay") {
							onAlipay(result.datas);
						}
					} else {
						loading?(layer.close(layer_loading),loading = false):false;
						layer.msg(result.err, {icon: 5,shade: [0.8, '#393D49'],time: 2000});
					}
				}

			},
			error: function(error) {
				loading?(layer.close(layer_loading),loading = false):false;
				layer.msg('网络连接失败', {icon: 5,shade: [0.8, '#393D49'],time: 2000});
			},
			complete: function(){
				$submit.removeClass('weui-btn_loading');
				loading?(layer.close(layer_loading),loading = false):false;
			}
		})
	}
	//微信
	function onWeixinPay(data) {	
		if (typeof WeixinJSBridge == "undefined") {	
				//点击支付超过三次
				payCount(function(){
					$.ajax({
						url: '/log_error',
						cache: false,
						data: 'WeixinJSBridge=' + WeixinJSBridge,
						method: 'post',
						success:function(res){
							location.reload();//刷新页面	
						},
						error: function(e){
							console('send log fail!');
						}
					});				
				});				
			if (document.addEventListener ) {
				document.addEventListener('WeixinJSBridgeReady', function(){weixinpay(data)}, false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', function(){weixinpay(data)});
				document.attachEvent('onWeixinJSBridgeReady', function(){weixinpay(data)});
			}
		} else {
			weixinpay(data);
		}
	}
	function weixinpay(data){
		WeixinJSBridge.invoke("getBrandWCPayRequest", {
			appId : data.appId, //公众号名称，由商户传入
			timeStamp : data.timeStamp, //时间戳，自1970年以来的秒数
			nonceStr : data.nonceStr, //随机串
			package : data.packages,
			signType : data.signType, //微信签名方式：
			paySign : data.paySign
		//微信签名
		}, function(res) {
			if (res.err_msg == "get_brand_wcpay_request:ok") {
				//支付成功的同步
//				location.href = "/member/advert/get?orderSn="+data.orderNo;
				showPayMark();	
			} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
				layer.alert('取消支付', {icon: 6});
	        } else if (res.err_msg == "get_brand_wcpay_request:fail") {
	        	layer.alert('支付失败', {icon: 5});
	        }else{
				$.ajax({
					url: '/log_error',
					cache: false,
					data: 'payError='+res,
					method: 'post',
					success:function(res){
						location.reload();//刷新页面	
					},
					error: function(e){
						console('send log fail!');
					}
				});	        	
	        }
			
		});
	}
	//支付宝
	function onAlipay(data) {
		//点击支付超过三次
		payCount(function(){
			$.ajax({
				url: '/log_error',
				cache: false,
				data: 'AlipayJSBridge=' + AlipayJSBridge,
				method: 'post',
				success:function(res){
					location.reload();//刷新页面	
				},
				error: function(e){
					console('send log fail!');
				}
			});				
		});		
		AlipayJSBridge.call("tradePay", {
			tradeNO : data.preTradeNo
		}, function(result) {
			if (result.resultCode == "9000") {
				//支付成功
				/*location.href = "/member/advert/get?orderSn="+data.orderNo;*/
				showPayMark();
			} else if (result.resultCode == "8000") {
				//正在处理
				layer_loading=layer.msg('查询停车费用', {
					  icon: 16
					  ,shade: 0.01
					  ,time: 1500
					});					
			} else if (result.resultCode == "4000") {
				//订单失败
				layer.msg('订单失败', {icon: 5});
			} else if (result.resultCode == "6001") {
				//中途取消
				layer.msg('支付失败', {icon: 5});
			} else if (result.resultCode == "6002") {
				//网络错误
				layer.msg('网络异常，请重试', {icon: 5});
			}
		});
	};
	
	//CarPlateInformation根据车牌查询信息
	function CarPlateInformation() {
		onQueryCarPlate();
		  setInterval(function(){
		  onQueryCarPlate();
		 }, 1000*5)	 
	};
	// 将分钟数量转换为小时和分钟字符串
	function toHourMinute(minutes) {
		return (Math.floor(minutes / 60) + "小时" + (minutes % 60) + "分");
	};	
	/** 点击切换车牌 */
	$(".plate-number").click(function() {
	  	$(".plate-select").show();
	  	$(".plate-select ul").show();		
	});
/** 缴费记录*/
	$(".park-record").click(function() {
		location.href = "/member/order/list";
	});
/** 点击支付*/
	$(".submit").click(function() {
		try{
			var money=allData.parkingInfo.fee,
			carPlateId=allData.carPlateId;//查询是不是月卡				
		}catch(err){
			layer.msg('未找到停车信息！', {icon:6,shade: [0.8, '#393D49'],time: 1000});
		}
		if(money==0){
			//判断一下是不是月卡；
			layer.msg('当前缴费金额为零，不需要下单！', {icon:6,shade: [0.8, '#393D49'],time: 2000});
		}else{
			createOrder();
		}		
	});

//充值月卡
	$(".park-card").click(function(){
//		location.href= "/member/monthcard"
		
	});
//车牌管理
	$('.park-admin').click(function(){
		location.href= "/member/carplate/list";
	});
//点击车牌列表
  $(".plate-select").click(function(){
  	var self=$(this);
  	$(".plate-select ul").slideToggle(500,function(){
  		self.hide();
  	});
  });
/*  选中车牌动作*/
  $('.plate-select').on('click',"li",function(){
  	var carPlate=$(this).text(),
  		carPlateId=$(this).attr('data-id');
  	allData.parkingInfo=null;//清空之前的数据，防止网络超时引起的数据缓存
	$('.submit').addClass('submit-disabled');
	$('.park-time .content').text('');
	$('.pay-money .money').text('');
	$('.Einlass .content').text('');
	$('.calcstarttime .content').text('');	  	
  	$('.plate-number .content').html(carPlate);
		allData.carPlateId =carPlateId;
		allData.carPlate =carPlate;
		queryParkingFee(); 	
  });  	
/*	月卡*/
  $('.user-table .card').click(function(){
	  window.location.href="/member/mcard/charge";
  });
 //
  $('#wrapper').on('click','.weui-footer',function(){
	  layer.alert('联系电话400-9663650',{btn: ['拨号','取消']}, function(index){	  
		  window.location.href='tel:400-9663650'
		  layer.close(index);
	});
  });
  //添加车牌
  $('.plate-select-title .bt').click(function(){
		var len=$('.plate-select ul').find('li').length;
			if(len>2){
					var addPlate=layer.alert('最多绑定3个车牌，请解绑一个后添加',{btn: ['确认','取消']}, function(index){	  
						  window.location.href='/member/carplate/list';
						  layer.close(index);
					});							
			}else{
				location.href = '/member/carplate/bind';
			}	  
  });
/* ----------19/0725 zb---*/
/*  支付成功回调*/
 ;Date.prototype.Format = function (fmt) {
	    var o = {
	        "M+": this.getMonth() + 1, //月份 
	        "d+": this.getDate(), //日 
	        "h+": this.getHours(), //小时 
	        "m+": this.getMinutes(), //分 
	        "s+": this.getSeconds(), //秒 
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	        "S": this.getMilliseconds() //毫秒 
	    };
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	}
;function getPayTime(){
  var date=new Date(),
      successTime=date.Format("yyyy-MM-dd hh:mm:ss");
  return successTime;
}
//支付成功遮罩
;function showPayMark(){
	var payTime=getPayTime();
	  $('.paySuccess-mark').show();
	  $('.paySuccess-mark .time').html(payTime);
}
//payCount=>支付点击数量
;function payCount(callBack){
    if(typeof window.payTime!=='undefined'){
      if(window.payTime>1){
    	  callBack()
      }else{
        window.payTime++;
      }
    }else{
      window.payTime=1;
    }
}
;$('.button').click(function(){
  if (/MicroMessenger/.test(window.navigator.userAgent)) { 
      WeixinJSBridge.call('closeWindow');
  } else if (/AlipayClient/.test(window.navigator.userAgent)) { 
      AlipayJSBridge.call('closeWebview');
  } else {
     // alert('其他浏览器');
  } 
});
  